package com.itheima.d5_synchronized_method;

import static java.lang.Thread.sleep;

/**
 * 目标：模拟线程安全问题。
 */
public class ThreadTest {


    public static void main(String[] args) {

        myRunnable myr=new myRunnable();

//        Thread thread1=new Thread(new myRunnable(),"窗口1");
//        Thread thread2=new Thread(new myRunnable(),"窗口2");
//        Thread thread3=new Thread(new myRunnable(),"窗口3");

        Thread thread1=new Thread(myr,"窗口1");
        Thread thread2=new Thread(myr,"窗口2");
        Thread thread3=new Thread(myr,"窗口3");

        thread1.start();
        thread2.start();
        thread3.start();
    }
}

class myRunnable implements Runnable{
//    private static int tickets=100;
private  int tickets=100;
    @Override
    public void run() {
        while(true){
           if(ishave()){
               try {
                   sleep(100);
               } catch (InterruptedException e) {
                   throw new RuntimeException(e);
               }

           }else{
               System.out.println("卖光了");
               break;

           }

        }
    }

    /**
     * 静态啊方法的锁对象是类.class
     * 实列方法的锁对象是this
     * @return
     */
    private synchronized boolean ishave(){
        if(tickets<=0){
            return false;
        }else {

            tickets--;
            System.out.println(Thread.currentThread().getName()+"正在卖票，还剩"+tickets+"张");
            return true;
        }
    }
}